<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="creatInfo"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">{{
          `${title} ${formData.planCode || ""}`
        }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <bigChange
            v-if="jobType == 'overhaul'"
            :allInfo="formData"
            :unEdit="unEdit"
            @producedTitle="producedTitle"
            ref="basicInfo"
          />
          <experiment
            v-if="jobType == 'experiment'"
            :allInfo="formData"
            :unEdit="unEdit"
            @producedTitle="producedTitle"
            ref="basicInfo"
          />
          <plannedMaintenance
            v-if="jobType == 'repair'"
            :allInfo="formData"
            :unEdit="unEdit"
            @producedTitle="producedTitle"
            ref="basicInfo"
          />
          <div class="upload-file">
            <label>上传附件</label>
            <attachFormNew
              style="width: 50%"
              :attachSetting="attachSetting"
              ref="attachForm"
              :isDelete="true"
              :disabled="unEdit"
            ></attachFormNew>
          </div>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="status > 0">
          <template slot="title">
            <span class="titleLine"></span>
            审批信息
          </template>
          <workFlow
            :isDetails="pageType == 'details'"
            :currentFlowData="formData"
            ref="workFlow"
            @submitSuccess="workFlowSuccess"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      title="提交"
      :show.sync="show"
      @doClose="() => (show = false)"
      :fullscreen="true"
      :noFootBtn="true"
      appendTobody
    >
      <workFlow
        v-if="show"
        :isDetails="pageType == 'query'"
        workflowCode="repair_plan_issue"
        :currentFlowData="formData"
        :beforeSubmit="beforeSubmit"
        ref="workFlow"
        @submitSuccess="workFlowInitSuccess"
      ></workFlow>
    </dialogPublic>
  </div>
</template>
<script>
import {
  getIssuePlanDetail,
  issuePlan,
  addOrUpdateIssuePlan,
  deleteIssuePlan,
} from "@/api/productionPlan/overhaulPlanPackage.js";
import bigChange from "./bigChange.vue";
import experiment from "./experiment.vue";
import plannedMaintenance from "./plannedMaintenance.vue";
export default {
  components: {
    bigChange,
    experiment,
    plannedMaintenance,
  },
  data() {
    return {
      title: "",
      activeNames: ["1", "2"],
      titleName: "",
      showInput: false,
      userInput: false,
      show: false,
      hideBtn: false,
      titleEdit: true,
      status: -1,
      pageType: "",
      formData: {},
      creatInfo: {},
      attachSetting: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      beforeSubmit: {
        methods: (data) => {
          return new Promise(async (resolve, reject) => {
            try {
              let formData = await this.$refs.basicInfo.getBasicInfo();
              formData.title = this.titleName;
              formData.jobType = this.jobType;
              this.formData = formData;
              resolve(formData);
            } catch (error) {
              reject(error);
            }
          });
        },
      },
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.status != 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("doSubmit"),
          methods: () => {
            this.show = true;
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) || this.status > 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            this.status != 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
        {
          text: "下发",
          icon: "el-icon-s-promotion",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            this.status != 2,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("issue"),
          methods: () => {
            this.issued();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {
        nowStep: this.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "待审核", "待下发", "已下发", "执行中", "已完成"],
      };
      return obj;
    },
    unChangeable() {
      return this.status == 1 || this.pageType == "detail";
    },
    unEdit() {
      return ["query", "detail"].includes(this.pageType) || this.status > 0;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let { id, pageType, jobType } = this.$route.query;
      this.formData.id = id;
      this.jobType = jobType;
      this.title =
        this.$store.getters.fineDirtDataName(
          "plan_package_type",
          this.jobType
        ) + "计划";
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.titleEdit = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //手动输入标题
    userInputTitle(val) {
      if (val != "") {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //初始化标题生成方式
    initTitleInput(form) {
      let equipmentName = form.equipments.map((i) => i.equipmentName).join(",");
      let title;
      if (form.jobType == "overhaul") {
        title = `${form.deptManageName || ""}${equipmentName || ""}大修`;
      } else if (form.jobType == "experiment") {
        title = `${form.deptManageName || ""}${equipmentName || ""}试验`;
      } else {
        title = `${form.deptManageName}${equipmentName}${form.content}`;
      }
      if (formData.title != title) {
        this.userInput = true;
      }
    },
    //生成标题
    producedTitle(title) {
      if (!this.userInput) {
        this.titleName = title;
      }
    },
    //获取标准详情
    getDetails(id) {
      getIssuePlanDetail({ issueId: id }).then((res) => {
        if (res.code == 200) {
          this.jobType = res.data.jobType;
          this.creatInfo = res.data;
          this.status = parseInt(res.data.status);
          this.attachSetting = {
            businessId: id,
          };
          this.title =
            this.$store.getters.fineDirtDataName(
              "plan_package_type",
              this.jobType
            ) + "计划";
          setTimeout(() => {
            this.formData = res.data;
            this.titleName = this.formData.title;
          }, 100);
          if (this.pageType != "detail") {
            if (this.status < 1) {
              this.hideBtn = false;
              this.titleEdit = true;
            } else {
              this.hideBtn = true;
              this.titleEdit = false;
            }
          }
        }
      });
    },
    //下发
    issued() {
      this.$confirm("确定要下发计划吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          issuePlan({ issueId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(
                this.formData.id,
                `下发了${this.title}`
              );
              this.updateListData();
              this.getDetails(this.formData.id);
            }
          });
        })
        .catch((e) => {});
    },
    //删除
    deleteId() {
      this.$confirm("确定要删除该条数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteIssuePlan({ issueId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(
                this.formData.id,
                `删除了${this.title}`
              );
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save() {
      try {
        let formData = await this.$refs.basicInfo.getBasicInfo();
        formData.title = this.titleName;
        formData.jobType = this.jobType;
        if (this.titleName == "") {
          this.loseFocus();
        } else {
          let res = await addOrUpdateIssuePlan(formData);
          await this.uploadFile(res.data.id);
          this.$message.success(res.description);
          this.updateListData();
          if (this.pageType == "add") {
            this.$utils.addOperateLog(res.data.id, `新建了${this.title}`);
            let obj = {
              id: res.data.id,
              pageType: "edit",
            };
            this.$router.push({
              query: obj,
            });
          } else {
            this.$utils.addOperateLog(this.formData.id, `修改了${this.title}`);
            this.getDetails(this.formData.id);
          }
        }
      } catch (error) {}
    },
    uploadFile(id) {
      new Promise((resolve, reject) => {
        this.attachSetting = { businessId: id };
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachForm.doSubmitFiles();
      });
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    //工作流成功后的回调函数
    workFlowSuccess() {
      this.updateListData();
      this.getDetails(this.formData.id);
      this.$refs.workFlow.initIframe();
    },
    //草稿状态工作流提交成功之后
    workFlowInitSuccess() {
      this.show = false;
      this.$utils.addOperateLog(this.formData.id, `提交了了${this.title}`);
      this.updateListData();
      this.getDetails(this.formData.id);
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  .upload-file {
    margin-left: 22px;
    text-align: left;
    display: flex;
    align-items: baseline;
    label {
      margin: 32px 12px 0 40px;
    }
  }
}
</style>
